<template>
  <div class="bg-white p-4 rounded-lg flex flex-col h-full overflow-hidden">
    <div class="flex justify-between items-center border-b border-gray-200 pb-4 mb-4">
      <div class="flex items-center space-x-4">
        <h2 class="text-xl font-bold">党支部管理</h2>
        <n-space>
          <n-tag type="info">总计: {{ totalCount }} 个党支部</n-tag>
          <n-tag type="success">当前页: {{ tableData.length }} 个</n-tag>
          <n-tag type="default" v-if="hasActiveFilters">已启用筛选</n-tag>
        </n-space>
      </div>

      <n-button text type="primary" @click="showControls = !showControls" class="flex items-center">
        <template #icon>
          <n-icon>
            <SettingsIcon v-if="!showControls" />
            <ChevronUpIcon v-else />
          </n-icon>
        </template>
        {{ showControls ? '收起控制面板' : '展开控制面板' }}
      </n-button>
    </div>

    <div class="flex-shrink-0">
      <n-collapse-transition :show="showControls">
        <n-space :vertical="true" class="mb-4">
          <n-card size="small" class="scroll-control-card">
            <n-space justify="space-between" align="center">
              <n-space align="center">
                <n-tag type="info" size="small">
                  <template #icon>
                    <n-icon>
                      <ArrowsHorizontalIcon />
                    </n-icon>
                  </template>
                  横向滚动控制
                </n-tag>
                <n-button size="small" @click="scrollToLeft" type="tertiary">
                  <template #icon><n-icon>
                      <ArrowLeftIcon />
                    </n-icon></template>
                  最左
                </n-button>
                <n-button size="small" @click="scrollToCenter" type="tertiary">
                  <template #icon><n-icon>
                      <FocusIcon />
                    </n-icon></template>
                  居中
                </n-button>
                <n-button size="small" @click="scrollToRight" type="tertiary">
                  <template #icon><n-icon>
                      <ArrowRightIcon />
                    </n-icon></template>
                  最右
                </n-button>
              </n-space>
              <n-space align="center">
                <n-slider v-model:value="scrollPosition" :min="0" :max="100" :step="1" style="width: 200px"
                  @update:value="handleScrollSlider" :tooltip="false" />
                <n-tag size="small" type="default">{{ scrollPosition }}%</n-tag>
              </n-space>
            </n-space>
          </n-card>

          <n-card size="small">
            <n-space justify="space-between" align="center">
              <n-space align="center">
                <n-input v-model:value="searchQuery" placeholder="按党支部名称、描述搜索" clearable style="width: 280px">
                  <template #prefix><n-icon>
                      <SearchIcon />
                    </n-icon></template>
                </n-input>
                <n-select v-model:value="selectedBranchType" :options="branchTypeOptions" placeholder="筛选支部类型" clearable
                  style="width: 150px" />
                <n-button @click="clearFilters" type="warning" size="medium">
                  <template #icon><n-icon>
                      <FilterOffIcon />
                    </n-icon></template>
                  清除筛选
                </n-button>
              </n-space>

              <n-space align="center">
                <n-button type="primary" size="medium" @click="handleAddBranch">
                  <template #icon><n-icon>
                      <PlusIcon />
                    </n-icon></template>
                  新建党支部
                </n-button>
                <n-popover trigger="click" placement="bottom-end">
                  <template #trigger>
                    <n-button type="default" size="medium">
                      <template #icon><n-icon>
                          <ColumnsIcon />
                        </n-icon></template>
                      筛选列 ({{ visibleColumns.length }}/{{ baseColumns.length }})
                    </n-button>
                  </template>
                  <div style="max-height: 400px; overflow-y: auto; width: 220px;">
                    <n-checkbox-group v-model:value="visibleColumns">
                      <n-space vertical>
                        <n-checkbox v-for="col in baseColumns" :key="col.key" :value="col.key" :label="col.title" />
                      </n-space>
                    </n-checkbox-group>
                  </div>
                </n-popover>
              </n-space>
            </n-space>
          </n-card>
        </n-space>
      </n-collapse-transition>
    </div>

    <div class="flex-1 min-h-0 overflow-hidden">
      <n-data-table ref="tableRef" :columns="columns" :data="tableData" :pagination="pagination" :bordered="false"
        :single-line="false" :loading="loading" :scroll-x="2000" size="small" striped @scroll="handleTableScroll"
        flex-height class="h-full" />
    </div>

    <!-- 新建党支部对话框 -->
    <n-modal v-model:show="showCreateModal" :mask-closable="false" preset="dialog" title="新建党支部">
      <n-form ref="createFormRef" :model="createForm" :rules="createRules" label-placement="left" label-width="auto" require-mark-placement="right-hanging">
        <n-form-item label="党支部名称" path="branchName">
          <n-input v-model:value="createForm.branchName" placeholder="请输入党支部名称" />
        </n-form-item>
        <n-form-item label="党支部类型" path="branchType">
          <n-select v-model:value="createForm.branchType" :options="branchTypeOptions" placeholder="请选择党支部类型" />
        </n-form-item>
        <n-form-item label="党支部描述" path="branchDescription">
          <n-input type="textarea" v-model:value="createForm.branchDescription" placeholder="请输入党支部描述" :rows="3" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showCreateModal = false">取消</n-button>
          <n-button type="primary" :loading="createLoading" @click="handleCreateBranch">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, computed, watch } from 'vue'
// 【修改点 1】: 导入 useRouter
import { useRouter } from 'vue-router'
import {
  NSpace, NInput, NSelect, NButton, NDataTable, NPopover,
  NCheckboxGroup, NCheckbox, NTag, NTooltip, NCard, NSlider, NIcon,
  NCollapseTransition, useMessage, NModal, NForm, NFormItem
} from 'naive-ui'
import {
  Search as SearchIcon,
  X as FilterOffIcon,
  Columns as ColumnsIcon,
  ArrowLeft as ArrowLeftIcon,
  ArrowRight as ArrowRightIcon,
  Focus as FocusIcon,
  ArrowsHorizontal as ArrowsHorizontalIcon,
  Settings as SettingsIcon,
  ChevronUp as ChevronUpIcon,
  Plus as PlusIcon
} from '@vicons/tabler'
import { getBranchList, createBranch } from '@/api/index.js'

// 【修改点 2】: 移除 defineEmits
// const emit = defineEmits(['view-details', 'add-branch'])

// 【修改点 3】: 获取 router 实例
const router = useRouter()
const message = useMessage()

// 新建党支部相关状态
const showCreateModal = ref(false)
const createLoading = ref(false)
const createFormRef = ref(null)

// 新建党支部表单数据
const createForm = ref({
  branchName: '',
  branchType: null,
  branchDescription: ''
})

// 表单验证规则
const createRules = {
  branchName: [
    { required: true, message: '请输入党支部名称', trigger: 'blur' }
  ],
  branchType: [
    { required: true, message: '请选择党支部类型', trigger: 'change' }
  ],
  branchDescription: [
    { required: true, message: '请输入党支部描述', trigger: 'blur' }
  ]
}

// 响应式数据 (保持不变)
const tableData = ref([])
const loading = ref(false)
const totalCount = ref(0)
const tableRef = ref(null)
const showControls = ref(true)

// 搜索和筛选 (保持不变)
const searchQuery = ref('')
const selectedBranchType = ref(null)

// 横向滚动控制 (保持不变)
const scrollPosition = ref(0)

// 筛选选项
const branchTypeOptions = [
  { label: '本科生党支部', value: '本科' },
  { label: '硕士研究生党支部', value: '硕士' },
  { label: '博士研究生党支部', value: '博士' }
]

// 分页配置 (保持不变)
const pagination = ref({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  itemCount: 0,
  prefix: ({ itemCount }) => `共 ${itemCount} 条`,
  onChange: (page) => {
    pagination.value.page = page
    loadData()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    loadData()
  },
})

// 表格列定义 (保持不变)
const baseColumns = [
  {
    title: '支部名称',
    key: 'branchName',
    width: 200,
    fixed: 'left',
    sorter: true,
    render(row) {
      const text = row.branchName || '-'
      if (text.length > 15) {
        return h(NTooltip,
          { trigger: 'hover' },
          {
            trigger: () => text.substring(0, 15) + '...',
            default: () => text
          }
        )
      }
      return text
    }
  },
  {
    title: '类型',
    key: 'branchType',
    width: 120,
    filterOptions: branchTypeOptions,
    filter: true,
    render(row) {
      const typeMap = {
        '本科': 'success',
        '硕士': 'info',
        '博士': 'warning'
      }
      return h(NTag, {
        type: typeMap[row.branchType] || 'default',
        size: 'small'
      }, { default: () => row.branchType + '生党支部' })
    }
  },
  {
    title: '正式党员数',
    key: 'formalMemberCount',
    width: 120,
    sorter: true,
    render(row) {
      const count = row.formalMemberCount || 0
      return h(NTag, {
        type: count > 0 ? 'success' : 'default',
        size: 'small'
      }, { default: () => count + ' 人' })
    }
  },
  {
    title: '积极分子党员数',
    key: 'activistCount',
    width: 140,
    sorter: true,
    render(row) {
      const count = row.activistCount || 0
      return h(NTag, {
        type: count > 0 ? 'info' : 'default',
        size: 'small'
      }, { default: () => count + ' 人' })
    }
  },
  {
    title: '党员数量',
    key: 'totalMemberCount',
    width: 100,
    sorter: true,
    render(row) {
      const count = (row.currentMembers || []).length
      return h(NTag, {
        type: count > 0 ? 'primary' : 'default',
        size: 'small'
      }, { default: () => count + ' 人' })
    }
  },
  {
    title: '支部书记',
    key: 'secretary',
    width: 120,
    render(row) {
      const currentCommittee = (row.branchCommittees || []).find(c => !c.endDate)
      if (!currentCommittee) return '-'

      const secretary = (currentCommittee.committeeMembers || []).find(m => m.positionHeld === '支部书记')
      const name = secretary ? secretary.memberName : '-'

      if (name.length > 8) {
        return h(NTooltip,
          { trigger: 'hover' },
          {
            trigger: () => name.substring(0, 8) + '...',
            default: () => name
          }
        )
      }
      return name
    }
  },
  { title: '操作', key: 'actions', fixed: 'right', width: 120 }
]

// 默认显示的列 (保持不变)
const visibleColumns = ref(baseColumns.map(col => col.key))

// 检查是否有活跃的筛选 (保持不变)
const hasActiveFilters = computed(() => {
  return searchQuery.value.length > 0 || selectedBranchType.value !== null
})

// 计算属性 - 表格列 (保持不变)
const columns = computed(() => {
  const actionColumn = {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    width: 120,
    render(row) {
      return h(NButton, {
        size: 'small',
        type: 'primary',
        onClick: () => handleViewDetails(row)
      }, { default: () => '查看详情' })
    }
  }

  return baseColumns
    .filter(col => visibleColumns.value.includes(col.key))
    .map(col => {
      if (col.key === 'actions') {
        return actionColumn
      }
      return col
    })
})

// 获取党支部列表数据
const fetchBranchList = async (params) => {
  try {
    const result = await getBranchList(params);
    // 确保返回的数据格式正确
    return {
      list: Array.isArray(result) ? result : (result.list || []),
      total: result.total || 0,
      page: result.page || 1,
      pageSize: result.pageSize || 20
    };
  } catch (error) {
    console.error('获取党支部列表失败:', error);
    return {
      list: [],
      total: 0,
      page: 1,
      pageSize: 20
    };
  }
}

// 加载数据主函数
const loadData = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      search: searchQuery.value,
      branchType: selectedBranchType.value
    }

    const result = await fetchBranchList(params)
    tableData.value = result.list
    totalCount.value = result.total
    pagination.value.itemCount = result.total

  } catch (error) {
    console.error('加载数据失败:', error)
    tableData.value = []
    totalCount.value = 0
    pagination.value.itemCount = 0
  } finally {
    loading.value = false
  }
}

const scrollToRight = async () => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()

  if (tableElement && tableElement.scrollWidth > tableElement.clientWidth) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    tableElement.scrollTo({ left: maxScrollLeft, behavior: 'smooth' })
    scrollPosition.value = 100
  }
}

const scrollToCenter = async () => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()

  if (tableElement && tableElement.scrollWidth > tableElement.clientWidth) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    const centerPosition = maxScrollLeft / 2
    tableElement.scrollTo({ left: centerPosition, behavior: 'smooth' })
    scrollPosition.value = 50
  }
}

const handleScrollSlider = async (value) => {
  await waitForNextTick()
  const tableElement = getTableScrollElement()
  if (tableElement) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    const targetScrollLeft = (maxScrollLeft * value) / 100
    tableElement.scrollTo({ left: targetScrollLeft })
  }
}

const getTableScrollElement = () => {
  if (!tableRef.value) return null
  const tableEl = tableRef.value.$el
  const selectors = [
    '.n-data-table-base-table-body',
    '.n-data-table__main',
    '.n-data-table-wrapper',
    '.n-scrollbar-container',
    '.n-scrollbar-content'
  ]
  for (const selector of selectors) {
    const element = tableEl.querySelector(selector)
    if (element && element.scrollWidth > element.clientWidth) {
      return element
    }
  }
  return tableEl
}
const waitForNextTick = () => new Promise(resolve => setTimeout(resolve, 0))
const handleTableScroll = (e) => {
  const element = e.target
  if (element.scrollWidth > element.clientWidth) {
    const scrollPercentage = (element.scrollLeft / (element.scrollWidth - element.clientWidth)) * 100
    scrollPosition.value = Math.round(scrollPercentage)
  }
}


// 清除筛选 (保持不变)
const clearFilters = () => {
  searchQuery.value = ''
  selectedBranchType.value = null
}

// --- 处理操作 (核心修改) ---

// 【修改点 4】: 修改 handleViewDetails 方法
const handleViewDetails = (branch) => {
  router.push({ name: 'branch-detail', params: { id: branch.branchId } });
}

// 【修改点 5】: 修改 handleAddBranch 方法
const handleAddBranch = () => {
  // 重置表单
  createForm.value = {
    branchName: '',
    branchType: null,
    branchDescription: ''
  }
  // 显示新建对话框
  showCreateModal.value = true
}

// 处理新建党支部
const handleCreateBranch = async () => {
  try {
    // 验证表单
    await createFormRef.value?.validate()
    
    createLoading.value = true
    message.loading('正在创建党支部...', { duration: 0 })
    
    // 调用创建API
    const result = await createBranch(createForm.value)
    
    if (result) {
      message.success('党支部创建成功！')
      showCreateModal.value = false
      // 重新加载数据
      await loadData()
    } else {
      message.error('创建失败，请重试')
    }
  } catch (error) {
    console.error('创建党支部失败:', error)
    if (error.message) {
      message.error(error.message)
    } else {
      message.error('创建党支部失败，请重试')
    }
  } finally {
    createLoading.value = false
  }
}

// 监听搜索条件变化 (保持不变)
watch([searchQuery, selectedBranchType], () => {
  pagination.value.page = 1
  loadData()
})

// 组件挂载时初始化 (保持不变)
onMounted(async () => {
  await loadData()
})


</script>

<style scoped>
.scroll-control-card {
  border: 1px solid #e0e0e6;
}

.n-button--tertiary {
  background-color: transparent;
}

.n-button--tertiary:hover {
  background-color: #f6f6f7;
}
</style>